package com.meatball.authorization.controller

import com.meatball.authorization.data.dto.CreateUserParams
import com.meatball.authorization.data.dto.UpdateUserParams
import com.meatball.authorization.data.dto.UserResponse
import com.meatball.authorization.data.entity.UserEntity
import com.meatball.authorization.service.UserService
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.Parameters
import io.swagger.v3.oas.annotations.enums.ParameterIn
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import java.util.*

@Tag(name = "用户管理")
@RestController
@RequestMapping("/api/management/user")
class UserController (
    private val userService: UserService
) {
    @Operation(summary = "新增用户信息")
    @PostMapping
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun crate(@RequestBody @Validated data: CreateUserParams) {
        userService.crate(data)
    }

    @Operation(summary = "获取用户列表")
    @GetMapping("/read-all")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun readAll() : Iterable<UserResponse> {
        return userService.readAll()
    }

    @Operation(summary = "根据ID查询用户信息")
    @Parameters(
        Parameter(name = "id", description = "角色ID", `in` = ParameterIn.PATH, example = "1773177147784040448")
    )
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun readById(@PathVariable id: Long): Optional<UserEntity> {
        return userService.readById(id)
    }

    @Operation(summary = "更新用户信息")
    @Parameters(
        Parameter(name = "id", description = "角色ID", `in` = ParameterIn.PATH, example = "1773177147784040448")
    )
    @PutMapping("/{id}")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun update(@PathVariable id: Long, @RequestBody @Validated params: UpdateUserParams) {
        userService.update(id, params)
    }

    @Operation(summary = "删除用户信息")
    @Parameters(
        Parameter(name = "id", description = "角色ID", `in` = ParameterIn.PATH, example = "1773177147784040448")
    )
    @DeleteMapping("/{id}")
    @PreAuthorize("hasAnyRole(@roleHandler.roles())")
    fun delete(@PathVariable id: Long) {
        userService.delete(id)
    }
}